package org.yiming.tools.mqtt.client.client.command;

import lombok.extern.slf4j.Slf4j;
import org.yiming.tools.mqtt.client.ApplicationContext;
import org.yiming.tools.mqtt.client.client.MqttClient;

import java.util.concurrent.CountDownLatch;

/**
 * @author renwenpeng
 * date  2022/3/25 4:50 下午
 */
@Slf4j
public class ReconnectCommand extends AbstractMqttCommand {

    private final String[] names = new String[]{"reconn"};

    public ReconnectCommand(ApplicationContext applicationContext) {
        super(applicationContext);
    }

    @Override
    public String[] name() {
        return names;
    }

    @Override
    int argsMinLength() {
        return 0;
    }

    @Override
    String apply(MqttClient mqttClient, String[] args) {
        if (mqttClient != null) {
            try {
                mqttClient.close();
                CountDownLatch countDownLatch = new CountDownLatch(1);
                mqttClient.init(countDownLatch);
                countDownLatch.await();
                return "reconn success";
            } catch (Exception e) {
                log.error("reconnect fail", e);
            }
            return null;
        }
        log.warn("no any mqttClient is selected");
        return null;
    }

    @Override
    public String[] helpContent() {
        return new String[]{"reconn"};
    }
}
